package com.xiaoyu.lanling.feature.chat.model.videomodel;

import android.graphics.Bitmap;
import android.media.ThumbnailUtils;

import com.xiaoyu.lanling.util.FileCreateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.provider.MediaStore.Images.Thumbnails.MICRO_KIND;

public class ChatVideoModel {

    public static ChatVideoModel videoToModel(String videoPath, long durationInMS) {
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MICRO_KIND);
        File firstImagePath = FileCreateUtils.createImageFile();
        try {
            FileOutputStream outputStream = new FileOutputStream(firstImagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);

            final String firstPicturePath = firstImagePath.getAbsolutePath();
            final int duration = getDurationInSecond(durationInMS);
            final int width = bitmap.getWidth();
            final int height = bitmap.getHeight();

            bitmap.recycle();
            outputStream.close();

            return new ChatVideoModel(videoPath, duration, firstPicturePath, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static int getDurationInSecond(long duration) {
        int durationInSecond = (int) (duration / 1000);
        if (durationInSecond <= 0) {
            durationInSecond = 1;
        }
        return durationInSecond;
    }

    public final String filePath;
    public final String firstPicture;
    public final int duration;
    public final int thumbWidth;
    public final int thumbHeight;

    public ChatVideoModel(final String filePath, final int duration, final String firstPicture, final int thumbWidth, final int thumbHeight) {
        this.filePath = filePath;
        this.duration = duration;
        this.firstPicture = firstPicture;
        this.thumbWidth = thumbWidth;
        this.thumbHeight = thumbHeight;
    }
}
